<template>
  <div class="container">
    <div class="app-container">
      <!--
        el-tree
        data是数据(树形结构)
        props是展示规则
        label 显示文字的是哪个字段，默认是label
        children 子级数据是存储在哪个字段，默认是children
        default-expand-al 默认展开所有
      -->
      <el-tree default-expand-all :data="data" :expand-on-click-node="false">
        <!-- 节点结构 -->
        <el-row slot-scope="{data}" style="width:100%;" type="flex" justify="space-between">
          <el-col>{{ data.name }}</el-col>
          <el-col :span="4">
            <el-row type="flex">
              <el-col :span="12">{{ data.managerName }}</el-col>
              <el-dropdown @command="operateDept($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-col>
        </el-row>
      </el-tree>
      <add-dept ref="addDept" :parent-id="currentId" :show-dialog.sync="showDialog" @updateList="initData" />
    </div>
  </div>
</template>
<script>
import { deleteDepartmentApi, getDepartmentApi } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import addDept from './components/addDept.vue'

export default {
  name: 'Department',
  components: { addDept },
  data() {
    return {
      // 定义变量
      data: [],
      // 弹框控制变量
      showDialog: false,
      // 点击行的id
      currentId: ''
    }
  },
  created() {
    this.initData()// 调用获取数据的接口
  },
  methods: {
    async initData() {
      // 请求函数（封装Api请求）
      const res = await getDepartmentApi()
      // console.log(res)
      // 数据加工处理（整理成树）
      const result = transListToTreeData(res, 0)
      // 赋值变量
      this.data = result
    },
    async operateDept(val, rowId) {
      this.currentId = rowId
      if (val === 'add') {
        // 打开弹框
        this.showDialog = true
      }
      if (val === 'edit') {
        // 获取数据，回显
        await this.$refs.addDept.reviewFormDate(rowId)
        // 打开弹框
        this.showDialog = true
      }
      if (val === 'del') {
        await this.$confirm('确定要删除吗？')
        // 调用删除Api
        await deleteDepartmentApi(rowId)
        // 提示删除成功
        this.$message.success('删除成功')
        // 重新拉去数据
        this.initData()
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 100px;
}
</style>
